﻿Imports System.Data
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraGrid
Imports DevExpress.XtraEditors
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraSplashScreen

Public Class PhieuNhap
    Private state As Integer '0 default 1 tao moi 2 sua
    Private Sub setReadonly(ByVal b As Boolean)
        Me.MaTextEdit.Properties.ReadOnly = b
        Me.NhacungcapSearchLookUpEdit.Properties.ReadOnly = b
        Me.NghiepvuTextEdit.Properties.ReadOnly = b
        Me.SohoadonTextEdit.Properties.ReadOnly = b
        Me.NgayhoadonTextEdit.Properties.ReadOnly = b
        Me.NgaynhapTextEdit.Properties.ReadOnly = b
        Me.NgaythanhtoanTextEdit.Properties.ReadOnly = b
        Me.DiachiTextEdit.Properties.ReadOnly = b
        Me.ThuesuatTextEdit.Properties.ReadOnly = b
        If b Then
            'không cho phép chỉnh sửa lưới
            Me.IGridView1.OptionsBehavior.Editable = False
            'Không cho thêm dòng trống cuối lưới
            Me.IGridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None
        Else
            Me.IGridView1.OptionsBehavior.Editable = True
            'Cho thêm dòng trống cuối lưới
            Me.IGridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom
        End If
    End Sub
    Private Sub chophepButtonChiTiet(ByVal b As Boolean)
        Me.BarButtonItemTaoMoiChiTiet.Enabled = b
        Me.BarButtonItemXoaChiTiet.Enabled = b
        Me.BarButtonItemHuyThayDoiChiTiet.Enabled = b
    End Sub
    Private Sub chophepButtonLuuXoa(ByVal b As Boolean)
        Me.BarButtonItemLuu.Enabled = b
        Me.BarButtonItemXoa.Enabled = b
        If b Then
            Me.BarButtonItemSua.Enabled = False
        Else
            Me.BarButtonItemSua.Enabled = True
        End If
    End Sub

    Private Sub BarButtonItemTaoMoi_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemTaoMoi.ItemClick
        Try
            Me.setReadonly(False)
            Me.chophepButtonLuuXoa(True)
            Me.chophepButtonChiTiet(True)
            Me.MaTextEdit.Focus()
            Me.NhapBindingSource.AddNew()
            Me.state = 1
        Catch ex As Exception

        End Try
    End Sub

    Private Sub HangHoa_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SplashScreenManager.ShowForm(GetType(WaitForm1))
        Me.KhachhangTableAdapter.Fill(Me.PcvgppDataSet.khachhang)
        Me.NhapTableAdapter.Fill(Me.PcvgppDataSet.nhap)
        Me.NhapchitietTableAdapter.Fill(Me.PcvgppDataSet.nhapchitiet)
        Me.HanghoaTableAdapter.Fill(Me.PcvgppDataSet.hanghoa)
        Me.Hanghoa_donvitinhTableAdapter.Fill(Me.PcvgppDataSet.hanghoa_donvitinh)
        Me.setReadonly(True)
        Me.chophepButtonLuuXoa(False)
        Me.chophepButtonChiTiet(False)
        Me.IGridView1.BestFitColumns()
        Me.NhapBindingSource.MoveLast()
        Me.state = 0
        Me.NhacungcapSearchLookUpEditView.BestFitColumns()
        SplashScreenManager.CloseForm()
    End Sub

    Private Sub BarButtonItemLuu_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemLuu.ItemClick
        Try
            Me.IGridView1.CloseEditor()
            Me.NhapBindingSource.EndEdit()
            Me.FKnhapchitietnhapBindingSource.EndEdit()
            If Me.PcvgppDataSet.HasChanges Then
                If DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muốn 'Lưu' không?", "Nhắc Nhở", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
                    Me.NhapTableAdapter.Update(Me.PcvgppDataSet.nhap)
                    Me.NhapchitietTableAdapter.Update(Me.PcvgppDataSet.nhapchitiet)
                    Me.setReadonly(True)
                    Me.chophepButtonLuuXoa(False)
                    Me.chophepButtonChiTiet(False)
                    Me.state = 0
                End If
            Else
                DevExpress.XtraEditors.XtraMessageBox.Show("Chưa có thông tin để lưu", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.setReadonly(True)
                Me.chophepButtonLuuXoa(False)
                Me.chophepButtonChiTiet(False)
                Me.state = 0
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Function ktMaTonTai() As Boolean 'để đảm bảo mã là duy nhất

        For index = 0 To Me.IGridView1.RowCount - 1
            If Me.IGridView1.GetRowCellValue(index, "ma") = Me.MaTextEdit.EditValue Then
                Return True
                Exit Function
            End If
        Next
        Return False
    End Function

    Private Sub MaTextEdit_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
        If Me.ktMaTonTai() And state Then
            Me.MaTextEdit.ErrorText = "Mã đã tồn tại"
            e.Cancel = True
        End If
    End Sub

    Private Sub BarButtonItemSua_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemSua.ItemClick
        Me.setReadonly(False)
        Me.chophepButtonLuuXoa(True)
        Me.chophepButtonChiTiet(True)
        Me.state = 2
    End Sub

    Private Sub BarButtonItemXoa_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemXoa.ItemClick
        If DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muốn 'Xóa' không?", "Nhắc Nhở", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
            Me.NhapBindingSource.RemoveCurrent()
            Me.NhapTableAdapter.Update(Me.PcvgppDataSet.nhap)
            Me.setReadonly(True)
            Me.chophepButtonLuuXoa(False)
            Me.chophepButtonChiTiet(False)
            Me.state = 0
        End If
    End Sub

    Private Sub BarButtonItemHuyThayDoi_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemHuyThayDoi.ItemClick
        Me.NhapBindingSource.EndEdit()
        If Me.PcvgppDataSet.HasChanges Then
            If DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muốn hủy tất cả những thay đổi đang làm không?", "Nhắc Nhở", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
                Me.PcvgppDataSet.RejectChanges()
            End If
        Else
            DevExpress.XtraEditors.XtraMessageBox.Show("Chưa có thay đổi dữ liệu!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub BarButtonItemFirst_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemFirst.ItemClick
        Me.NhapBindingSource.MoveFirst()
    End Sub

    Private Sub BarButtonItem2_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Me.NhapBindingSource.MovePrevious()
    End Sub

    Private Sub BarButtonItem6_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem6.ItemClick
        Me.NhapBindingSource.MoveNext()
    End Sub

    Private Sub BarButtonItem7_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem7.ItemClick
        Me.NhapBindingSource.MoveLast()
    End Sub
    Private Sub batFocusGrid()
        'bắt focus trên lưới
        Me.IGridView1.FocusedRowHandle = 2
        Me.IGridView1.FocusedColumn = Me.IGridView1.VisibleColumns(0)
        Me.IGridView1.ShowEditor()
    End Sub

    Private Sub BarButtonItemTaoMoiChiTiet_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemTaoMoiChiTiet.ItemClick
        Me.IGridView1.Focus()
        Me.IGridView1.AddNewRow()
        Me.batFocusGrid()
    End Sub

    Private Sub BarButtonItemXoaChiTiet_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemXoaChiTiet.ItemClick
        If DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muốn xóa dòng đang chọn không?", "Nhắc Nhở", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
            Dim view As GridView = CType(IGridView1, GridView)
            view.DeleteRow(view.FocusedRowHandle)
        End If
    End Sub

    Private Sub BarButtonItemHuyThayDoiChiTiet_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemHuyThayDoiChiTiet.ItemClick
        Me.IGridView1.CloseEditor()
        Me.NhapchitietBindingSource.EndEdit()
        If PcvgppDataSet.HasChanges Then
            If DevExpress.XtraEditors.XtraMessageBox.Show("Bạn có muốn hủy những thay đổi đang làm không?", "Nhắc Nhở", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
                Me.PcvgppDataSet.RejectChanges()
            End If
        Else
            DevExpress.XtraEditors.XtraMessageBox.Show("Chưa có thông tin thay đổi!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub BarButtonItemFirstChiTiet_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemFirstChiTiet.ItemClick
        Me.NhapchitietBindingSource.MoveFirst()
    End Sub

    Private Sub BarButtonItemPreviousChiTiet_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemPreviousChiTiet.ItemClick
        Me.NhapchitietBindingSource.MovePrevious()
    End Sub

    Private Sub BarButtonItemNextChiTiet_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemNextChiTiet.ItemClick
        Me.NhapchitietBindingSource.MoveNext()
    End Sub

    Private Sub BarButtonItemLastChiTiet_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemLastChiTiet.ItemClick
        Me.NhapchitietBindingSource.MoveLast()
    End Sub

    Private Sub IGridView1_CellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles IGridView1.CellValueChanged
        Dim view1 As GridView = CType(sender, GridView)
        If Me.IGridView1.FocusedColumn.FieldName = "mahanghoa" Then
            Dim view As DataView = New DataView(Me.PcvgppDataSet.hanghoa_donvitinh)
            view.RowFilter = "hanghoa = '" & Me.IGridView1.GetRowCellValue(Me.IGridView1.FocusedRowHandle, "mahanghoa") & "'"
            Me.RepositoryItemSearchLookUpEdit3.DataSource = view
        End If
        '===================== xử lý thành tiền =======================
        Dim quantity As Decimal = 0
        Dim unitPrice As Decimal = 0
        Try
            quantity = CDec(view1.GetRowCellValue(e.RowHandle, view1.Columns("soluong")))
            unitPrice = CDec(view1.GetRowCellValue(e.RowHandle, view1.Columns("gia")))
        Catch ex As Exception

        End Try

        If e.Column.FieldName = "gia" Then
            view1.SetRowCellValue(e.RowHandle, view1.Columns("thanhtien"), quantity * unitPrice)
        End If
    End Sub


    Private Sub IGridView1_InvalidRowException(sender As Object, e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles IGridView1.InvalidRowException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction
    End Sub

    Private Sub NgayhoadonTextEdit_GotFocus(sender As Object, e As System.EventArgs) Handles NgayhoadonTextEdit.GotFocus
        Me.NgayhoadonTextEdit.ShowPopup()
    End Sub

    Private Sub NgaynhapTextEdit_GotFocus(sender As Object, e As System.EventArgs) Handles NgaynhapTextEdit.GotFocus
        Me.NgaynhapTextEdit.ShowPopup()
    End Sub

    Private Sub NgaythanhtoanTextEdit_GotFocus(sender As Object, e As System.EventArgs) Handles NgaythanhtoanTextEdit.GotFocus
        Me.NgaythanhtoanTextEdit.ShowPopup()
    End Sub

    Private Sub BarButtonItemThoat_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemThoat.ItemClick
        Me.Close()
    End Sub

    Private Sub IGridView1_InvalidValueException(sender As Object, e As DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs) Handles IGridView1.InvalidValueException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.DisplayError
    End Sub

    Private Sub IGridView1_ShownEditor(sender As Object, e As System.EventArgs) Handles IGridView1.ShownEditor
        Dim view As GridView = CType(sender, GridView)
        If TypeOf view.ActiveEditor Is SearchLookUpEdit And IsDBNull(Me.IGridView1.FocusedValue) Then
            DirectCast(view.ActiveEditor, SearchLookUpEdit).ShowPopup()
        End If
        Dim view1 As ColumnView = CType(sender, ColumnView)
        view1.ActiveEditor.IsModified = True
    End Sub

    Private Sub IGridView1_ValidateRow(sender As Object, e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles IGridView1.ValidateRow
        Dim view As ColumnView = CType(sender, ColumnView)
        Dim tenhanghoa As GridColumn = view.Columns("tenhanghoa")
        Dim bVali As Boolean = True
        ' kiem tra 2 cell cua mot dong dang Edit xem co rong ko?

        If IGridView1.GetRowCellValue(e.RowHandle, "mahanghoa").ToString() = "" Then
            bVali = False
            'sErr = sErr & "Vui long dien Ma hàng"
            view.SetColumnError(tenhanghoa, "tên hàng hóa không được rỗng")
        End If
        If IGridView1.GetRowCellValue(e.RowHandle, "tenhanghoa").ToString() = "" Then
            bVali = False
            'sErr = sErr & "Vui long dien Ten hàng"
            view.SetColumnError(tenhanghoa, "tên hàng hóa không được rỗng")
        End If
        If bVali = True Then
        Else
            e.Valid = False
        End If
    End Sub

    Private Sub IGridView1_ValidatingEditor(sender As Object, e As DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs) Handles IGridView1.ValidatingEditor
        Dim View As GridView = sender
        If View.FocusedColumn.FieldName = "mahanghoa" And View.FocusedRowHandle <> -999997 Then
            'If e.Value Is DBNull.Value Then
            If IsDBNull(e.Value) Or IsNothing(e.Value) Then
                e.ErrorText = "Mã hàng hóa không được rỗng !"
                e.Valid = False
            ElseIf e.Value.ToString = "" Then
                e.ErrorText = "Mã hàng hóa không được rỗng !"
                e.Valid = False
            End If
        End If
        If View.FocusedColumn.FieldName = "tenhanghoa" And View.FocusedRowHandle <> -999997 Then
            'If e.Value Is DBNull.Value Then
            If IsDBNull(e.Value) Or IsNothing(e.Value) Then
                e.ErrorText = "Tên hàng hóa không được rỗng !"
                e.Valid = False
            ElseIf e.Value.ToString = "" Then
                e.ErrorText = "Tên hàng hóa không được rỗng !"
                e.Valid = False
            End If
        End If
        If View.FocusedColumn.FieldName = "soluong" And View.FocusedRowHandle <> -999997 Then
            'If e.Value Is DBNull.Value Then
            If IsDBNull(e.Value) Or IsNothing(e.Value) Then
                e.ErrorText = "số lượng hóa không được rỗng !"
                e.Valid = False
            ElseIf e.Value.ToString = "" Or CInt(e.Value) = 0 Then
                e.ErrorText = "số lượng không được bằng 0 !"
                e.Valid = False
            End If
        End If
    End Sub

    Private Sub RepositoryItemSearchLookUpEdit2_EditValueChanging(sender As Object, e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles RepositoryItemSearchLookUpEdit2.EditValueChanging
        Dim editor As SearchLookUpEdit = CType(sender, SearchLookUpEdit)
        Dim rowHandle As Integer = editor.Properties.GetIndexByKeyValue(e.NewValue)
        IGridView1.SetFocusedRowCellValue("tenhanghoa", editor.Properties.View.GetRowCellValue(rowHandle, "ten"))
        IGridView1.SetFocusedRowCellValue("mahanghoa", editor.Properties.View.GetRowCellValue(rowHandle, "ma"))
    End Sub

    Private Sub RepositoryItemSearchLookUpEdit3_EditValueChanging(sender As Object, e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles RepositoryItemSearchLookUpEdit3.EditValueChanging
        Dim editor As SearchLookUpEdit = CType(sender, SearchLookUpEdit)
        Dim rowHandle As Integer = editor.Properties.GetIndexByKeyValue(e.NewValue)
        IGridView1.SetFocusedRowCellValue("tendvt", editor.Properties.View.GetRowCellValue(rowHandle, "ten"))
        IGridView1.SetFocusedRowCellValue("madvt", editor.Properties.View.GetRowCellValue(rowHandle, "ma"))
    End Sub

    'Private Sub BarButtonItemIn_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemIn.ItemClick
    '    Me.IGridControl1.ShowRibbonPrintPreview()
    'End Sub

    Private Sub NhacungcapSearchLookUpEdit_EditValueChanging(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles NhacungcapSearchLookUpEdit.EditValueChanging
        Dim editor As SearchLookUpEdit = CType(sender, SearchLookUpEdit)
        Dim rowhandle As Integer = Me.NhacungcapSearchLookUpEdit.Properties.GetIndexByKeyValue(e.NewValue)
        Me.DiachiTextEdit.EditValue = editor.Properties.View.GetRowCellValue(rowhandle, "diachi")
    End Sub

    Private Sub NhacungcapSearchLookUpEdit_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles NhacungcapSearchLookUpEdit.GotFocus
        Me.NhacungcapSearchLookUpEdit.ShowPopup()
    End Sub

    Private Sub NhacungcapSearchLookUpEdit_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles NhacungcapSearchLookUpEdit.KeyDown
        If (e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Tab) And (state = 1 Or state = 2) Then
            IGridView1.AddNewRow() 'thêm dòng mới
            Me.IGridView1.SetFocusedRowCellValue("ma", Me.MaTextEdit.EditValue)
            Me.IGridView1.SetFocusedRowCellValue("tenhanghoa", "")
            batFocusGrid()
            Dim col As GridColumn = IGridView1.Columns("mahanghoa")
            Me.IGridView1.FocusedColumn = col
            IGridView1.ShowEditor()
            Dim editor As SearchLookUpEdit = TryCast(IGridView1.ActiveEditor, SearchLookUpEdit)
            editor.ShowPopup()
        End If
    End Sub

    Private Sub IGridControl1_ProcessGridKey(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles IGridControl1.ProcessGridKey
        If (e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Tab) And (state = 1 Or state = 2) AndAlso Me.IGridView1.FocusedColumn.FieldName.Equals("vitri") Then
            Me.IGridView1.AddNewRow()
            Me.IGridView1.SetFocusedRowCellValue("ma", Me.MaTextEdit.EditValue)
            Me.IGridView1.SetFocusedRowCellValue("tenhanghoa", "")
            Dim col As GridColumn = IGridView1.Columns("mahanghoa")
            Me.IGridView1.FocusedColumn = col
            Me.IGridView1.ShowEditor()
            Dim editor As SearchLookUpEdit = TryCast(IGridView1.ActiveEditor, SearchLookUpEdit)
            editor.ShowPopup()
        End If
    End Sub

    Private Sub ShowGridPreview()
        ' Check whether the XtraGrid control can be previewed. 
        If Not IGridControl1.IsPrintingAvailable Then
            MessageBox.Show("The 'DevExpress.XtraPrinting' Library is not found", "Error")
            Return
        End If
        ' Opens the Preview window. 
        'Me.IGridControl1.ShowPrintPreview()
        'IGridControl1.ShowRibbonPrintPreview()
        Me.IGridControl1.ShowRibbonPrintPreview()
    End Sub
    Private Sub BarButtonItemIn_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItemIn.ItemClick
        ShowGridPreview()
    End Sub
End Class